package com.iyundao.io.Service.Impl;

import com.iyundao.io.Service.SysDeptService;
import com.iyundao.io.mapper.SysDeptCustomMapper;
import com.iyundao.io.mapper.SysDeptMapper;
import com.iyundao.io.mapper.SysDeptSqlMapper;
import com.iyundao.io.mapper.SysDeptSqlProvider;
import com.iyundao.io.model.SysDept;
import com.iyundao.io.model.SysDeptProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by black on 2019/4/27.
 */
@Service
@Transactional
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    SysDeptSqlMapper sysDeptSqlMapper;

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    SysDeptCustomMapper customMapper;

    @Override
    public List<SysDeptProvider> getAllTree() {
        return getTree("0");
    }

    @Override
    public List<SysDeptProvider> getTreeByParentId(String parentId) {
        return sysDeptSqlMapper.selectTreeBySid(parentId);
    }

    @Override
    public int addNewTree(SysDept sysDept) {
        return sysDeptMapper.insertSelective(sysDept);
    }

    @Override
    public int updateDept(SysDept sysDept) {
        return sysDeptMapper.updateByPrimaryKey(sysDept);
    }

    @Override
    public SysDeptProvider selectByRoleId(String sid) {
        SysDeptProvider sysDeptProvider = customMapper.selectBySid(sid);
        List<SysDeptProvider> list = customMapper.selectByParentId(sid);
        sysDeptProvider.setChild(list);
        return sysDeptProvider;
    }

    private List<SysDeptProvider> getOneTree(String parentId){
        return sysDeptSqlMapper.selectTreeByParentId(parentId);
    }

    private List<SysDeptProvider> getTree(String parentId){
        List<SysDeptProvider> list = getOneTree(parentId);
        for(SysDeptProvider sysDeptProvider : list){
            sysDeptProvider.setChild(getTree(sysDeptProvider.getSid()));
        }
        return list;
    }
}
